package com.hankol.newretail.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.baselibrary.utils.GlideUtils;
import com.baselibrary.utils.NumberUtils;
import com.hankol.newretail.R;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

/**
 * @author: 关忆北、
 * @date: 2022/8/2
 * @Des：
 */
public class GoodsVideoView extends RelativeLayout {
    public TXCloudVideoView mTxclGoodsDetVideo;
    public ImageView mIvGoodsDetPlay, mIvVideoCover, mIvGoodsDetVoice, ivGoodsDetFullVoice;
    public TextView mTvGoodsVideoSpeed, mTvGoodsVideoTotalSpeed;
    public SeekBar mSbGoodsDetVoice, sbGoodsVideoSpeed;
    public SeekBar originalSbGoodsDetVoice;//记录原始的播放进度view，主要是记录地址值
    public TXVodPlayer mVodPlayer;
    public ProgressBar mPbGoodsDetLoading;
    public int resultCode = -1;
    public String videoUrl = "";
    public String videoCover = "";
    public boolean isVoice = true;
    private OnVoiceClickListener mOnVoiceClickListener;
    private OnPlayCompleteCallBack mOnPlayCompleteCallBack;
    public RelativeLayout rlGoodsVideoSpeed;
    public int playMode = 1;//小屏幕
    private View videoView;
    private long playDuration = 0L;
    int UP_DATE_PLAYER = 0x101;

    private Handler tHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            mIvGoodsDetPlay.setVisibility(GONE);
            return false;
        }
    });

    public long getPlayDuration() {
        return playDuration;
    }

    public void setPlayDuration(long playDuration) {
        this.playDuration = playDuration;
    }

    public GoodsVideoView(Context context) {
        super(context);
        initView();
    }

    public GoodsVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public GoodsVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    public GoodsVideoView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView();
    }

    public TXVodPlayer getVodPlayer() {
        return mVodPlayer;
    }

    public void setOnVoiceClickListener(OnVoiceClickListener mOnVoiceClickListener) {
        this.mOnVoiceClickListener = mOnVoiceClickListener;
    }

    public void setOnPlayCompleteCallBack(OnPlayCompleteCallBack mOnPlayCompleteCallBack) {
        this.mOnPlayCompleteCallBack = mOnPlayCompleteCallBack;
    }

    public void visibilityCover() {
        mIvVideoCover.setVisibility(GONE);
        mIvGoodsDetPlay.setVisibility(GONE);
        mPbGoodsDetLoading.setVisibility(GONE);
    }


    private void initView() {
        videoView = LayoutInflater.from(getContext()).inflate(R.layout.view_goods_cover_video, this);
        mTxclGoodsDetVideo = (TXCloudVideoView) findViewById(R.id.txcl_goods_det_video);
        mIvVideoCover = (ImageView) findViewById(R.id.iv_goods_det_video_cover);
        mIvGoodsDetPlay = (ImageView) findViewById(R.id.iv_goods_det_play);
        mPbGoodsDetLoading = (ProgressBar) findViewById(R.id.pb_goods_det_loading);
        mIvGoodsDetVoice = (ImageView) findViewById(R.id.iv_goods_det_voice);
        mSbGoodsDetVoice = (SeekBar) findViewById(R.id.sb_goods_det_voice);
        originalSbGoodsDetVoice = mSbGoodsDetVoice;


        ivGoodsDetFullVoice = (ImageView) findViewById(R.id.iv_goods_det_fullVoice);//全屏
        mTvGoodsVideoSpeed = (TextView) findViewById(R.id.tv_goodsVideo_speed);//全屏
        mTvGoodsVideoTotalSpeed = (TextView) findViewById(R.id.tv_goodsVideo_totalSpeed);//全屏

        sbGoodsVideoSpeed = (SeekBar) findViewById(R.id.sb_goodsVideo_speed);//全屏
        rlGoodsVideoSpeed = (RelativeLayout) findViewById(R.id.ll_goods_video_speed);//全屏
        mTxclGoodsDetVideo.setLogMargin(12f, 12f, 110f, 60f);
        mTxclGoodsDetVideo.showLog(false);
        mTxclGoodsDetVideo.setKeepScreenOn(true);
        mIvGoodsDetVoice.setSelected(true);
        ivGoodsDetFullVoice.setSelected(true);

        initListener();
    }

    public void setPlayMode(int playMode) {
        this.playMode = playMode;
        if (playMode == 1) {
            rlGoodsVideoSpeed.setVisibility(GONE);
            mIvGoodsDetVoice.setVisibility(VISIBLE);
            mSbGoodsDetVoice.setVisibility(VISIBLE);
        } else if (playMode == 2) {
            rlGoodsVideoSpeed.setVisibility(VISIBLE);
            mIvGoodsDetVoice.setVisibility(GONE);
            mSbGoodsDetVoice.setVisibility(GONE);
            videoView.setOnClickListener(view -> {
                mIvGoodsDetPlay.setVisibility(mIvGoodsDetPlay.getVisibility() == GONE ? VISIBLE : GONE);
                hideDelayedPlay();
            });
        } else if (playMode == 3) {
            //弹窗
            mIvGoodsDetPlay.setVisibility(GONE);
            rlGoodsVideoSpeed.setVisibility(GONE);
            mIvGoodsDetVoice.setVisibility(GONE);
            mSbGoodsDetVoice.setVisibility(VISIBLE);
        }
    }

    public void isVoice(boolean isVoice) {
        mIvGoodsDetVoice.setSelected(isVoice);
        ivGoodsDetFullVoice.setSelected(true);
        if (mVodPlayer != null) {
            if (isVoice) {
                mVodPlayer.setMute(false);//有音设置
            } else {
                mVodPlayer.setMute(true);//静音设置
            }
        }
        mIvGoodsDetVoice.setImageResource(isVoice ? R.drawable.ic_material_voice_true : R.drawable.ic_material_voice_false);
        ivGoodsDetFullVoice.setImageResource(isVoice ? R.drawable.ic_material_voice_true : R.drawable.ic_material_voice_false);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        rlGoodsVideoSpeed.setOnTouchListener((@SuppressLint("ClickableViewAccessibility") View view, MotionEvent event) -> {
            Rect seekRect = new Rect();
            sbGoodsVideoSpeed.getHitRect(seekRect);

            if ((event.getY() >= (seekRect.top - 50)) && (event.getY() <= (seekRect.bottom + 50))) {

                float y = seekRect.top + seekRect.height() / 2;
                float x = event.getX() - seekRect.left;
                if (x < 0) {
                    x = 0;
                } else if (x > seekRect.width()) {
                    x = seekRect.width();
                }
                MotionEvent me = MotionEvent.obtain(event.getDownTime(), event.getEventTime(),
                        event.getAction(), x, y, event.getMetaState());
                return sbGoodsVideoSpeed.onTouchEvent(me);

            }
            return false;
        });
        sbGoodsVideoSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            private int mSlidePro;

            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                mSlidePro = seekBar.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (mVodPlayer != null)
                    mVodPlayer.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //手指抬起获取当前SeekBar进度
                if (mVodPlayer != null) {
                    mVodPlayer.seek(mSlidePro / 1000);
                    mVodPlayer.resume();
                    upPlayView(true);
                }
            }
        });

        mIvGoodsDetPlay.setOnClickListener(view -> {
            if (mVodPlayer != null) {
                if (mVodPlayer.isPlaying()) {
                    mVodPlayer.pause();
                    upPlayView(false);
                } else {
                    startPlay();
                }
            }
        });
        mIvGoodsDetVoice.setOnClickListener(view -> {
            if (mVodPlayer != null) {
                if (mIvGoodsDetVoice.isSelected()) {
                    isVoice = false;
                    mVodPlayer.setMute(true);//静音设置
                } else {
                    isVoice = true;
                    mVodPlayer.setMute(false);//有音设置
                }
                mIvGoodsDetVoice.setSelected(!mIvGoodsDetVoice.isSelected());
                if (mOnVoiceClickListener != null) mOnVoiceClickListener.onVoiceClick(isVoice);
                mIvGoodsDetVoice.setImageResource(isVoice ? R.drawable.ic_material_voice_true : R.drawable.ic_material_voice_false);
                ivGoodsDetFullVoice.setImageResource(isVoice ? R.drawable.ic_material_voice_true : R.drawable.ic_material_voice_false);
            }
        });
        ivGoodsDetFullVoice.setOnClickListener(view -> {
            if (mVodPlayer != null) {
                if (mIvGoodsDetVoice.isSelected()) {
                    isVoice = false;
                    mVodPlayer.setMute(true);//静音设置
                } else {
                    isVoice = true;
                    mVodPlayer.setMute(false);//有音设置
                }
                mIvGoodsDetVoice.setSelected(!mIvGoodsDetVoice.isSelected());
                if (mOnVoiceClickListener != null) mOnVoiceClickListener.onVoiceClick(isVoice);
                mIvGoodsDetVoice.setImageResource(isVoice ? R.drawable.ic_material_voice_true : R.drawable.ic_material_voice_false);
                ivGoodsDetFullVoice.setImageResource(isVoice ? R.drawable.ic_material_voice_true : R.drawable.ic_material_voice_false);
            }
        });

    }

    public void setVideoUrl(String videoUrl, String videoCover) {
        this.videoUrl = videoUrl;
        this.videoCover = videoCover;
        GlideUtils.loadImg_228(getContext().getApplicationContext(), videoCover, mIvVideoCover);
        initVideo();
    }


    public void setVideoCover(String videoUrl, String videoCover) {
        this.videoUrl = videoUrl;
        this.videoCover = videoCover;
        GlideUtils.loadImg_228(getContext().getApplicationContext(), videoCover, mIvVideoCover);
    }

    public void seek(long playDuration) {
        if (mVodPlayer != null) {
            mVodPlayer.seek(playDuration / 1000);
            mVodPlayer.resume();
            upPlayView(true);
        }
    }

    public void startPlay() {
        if (mVodPlayer != null) {
            if (resultCode != -1) {
                //已经播放过了
                mVodPlayer.resume();
                upPlayView(true);
                hideDelayedPlay();
            } else {
                //还没播放过
                mPbGoodsDetLoading.setVisibility(VISIBLE);
                resultCode = mVodPlayer.startVodPlay(videoUrl);
            }
        }
    }

    private void hideDelayedPlay() {
        tHandler.removeMessages(UP_DATE_PLAYER);
        tHandler.sendEmptyMessageDelayed(UP_DATE_PLAYER, 1000 * 2);
    }

    /**
     * 更新播放按钮的状态
     *
     * @param b
     */
    public void upPlayView(boolean b) {
        if (b) {

            mIvVideoCover.setVisibility(GONE);
            mIvGoodsDetPlay.setVisibility(GONE);
            mIvGoodsDetPlay.setSelected(true);
            mIvGoodsDetPlay.setImageResource(R.drawable.ic_material_play_ing);
        } else {
            if (playMode != 2) {
                mIvVideoCover.setVisibility(VISIBLE);
            }
            mIvGoodsDetPlay.setVisibility(VISIBLE);
            mIvGoodsDetPlay.setSelected(false);
            mIvGoodsDetPlay.setImageResource(R.drawable.icon_detail_play);
        }
    }

    public boolean isPlay() {
        if (mVodPlayer != null) {
            return mVodPlayer.isPlaying();
        }
        return false;
    }

    public void stopPlay() {
        if (mVodPlayer != null && mVodPlayer.isPlaying()) {
            mVodPlayer.pause();
        }
    }


    private void initVideo() {
        if (mVodPlayer != null) {
            mTxclGoodsDetVideo.setKeepScreenOn(true);
            mVodPlayer.setPlayerView(mTxclGoodsDetVideo);
            mVodPlayer.setAutoPlay(true);
            mVodPlayer.enableHardwareDecode(false); // 是否使用硬解码
            mVodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT); // player 渲染角度

            //        TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN 铺满全屏不留黑边
//        TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION 将图像等比缩放，适配最长边，存在黑边风险
            mVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);
            mVodPlayer.setVodListener(new ITXVodPlayListener() {
                @Override
                public void onPlayEvent(TXVodPlayer txVodPlayer, int event, Bundle bundle) {
                    switch (event) {
                        case TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED:
                            if (mIvVideoCover.getVisibility() == VISIBLE) {
                                mIvVideoCover.setVisibility(GONE);
                            }
                            if (playDuration > 0) {
                                mVodPlayer.seek(playDuration / 1000);
                                mVodPlayer.resume();
                            }
                            mPbGoodsDetLoading.setVisibility(GONE);
                            upPlayView(true);
                            break;
                        case TXLiveConstants.PLAY_EVT_PLAY_END:
                            if (mOnPlayCompleteCallBack != null) {
                                if (mVodPlayer.getCurrentPlaybackTime() > 0) {
                                    //视为播放完成
                                    mOnPlayCompleteCallBack.onPlayComplete();
                                }
                            }
                            mVodPlayer.seek(0);
                            upPlayView(false);
                            mIvVideoCover.setVisibility(VISIBLE);//显出封面
                            break;
                        case TXLiveConstants.PLAY_EVT_PLAY_LOADING:
                        case TXLiveConstants.PLAY_ERR_NET_DISCONNECT:
                            //视频流加载loading
                            mPbGoodsDetLoading.setVisibility(View.VISIBLE);
                            break;
                        case TXLiveConstants.PLAY_EVT_VOD_LOADING_END:
                            //视频流加载loading结束
                            mPbGoodsDetLoading.setVisibility(View.GONE);
                            break;
                        case TXLiveConstants.PLAY_EVT_PLAY_PROGRESS:
                            int progress = bundle.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);
                            int duration = bundle.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);

                            if (mSbGoodsDetVoice.getMax() != duration) {
                                //只設置一次即可
                                mTvGoodsVideoTotalSpeed.setText("/" + NumberUtils.stringForTime(duration));
                                mSbGoodsDetVoice.setMax(duration);
                                sbGoodsVideoSpeed.setMax(duration);
                            }
                            playDuration = progress;
                            mTvGoodsVideoSpeed.setText(NumberUtils.stringForTime(progress));
                            mSbGoodsDetVoice.setProgress(progress);
                            sbGoodsVideoSpeed.setProgress(progress);
                            break;
                    }
                }

                @Override
                public void onNetStatus(TXVodPlayer txVodPlayer, Bundle bundle) {

                }
            });
        }
    }

    public interface OnVoiceClickListener {
        void onVoiceClick(boolean b);
    }

    public interface OnPlayCompleteCallBack {
        void onPlayComplete();//播放完成
    }
}
